<template>
  <vab-dialog v-model="dialogFormVisible" append-to-body :title="title" :width="width" @close="close">
    <el-form ref="formRef" :model="form" label-width="130px" :rules="rules">
      <el-row>
        <el-col :span="span">
          <el-form-item label="旧密码">
            <el-input type="password" placeholder="请输入旧密码" show-password v-model.trim="form.old_password" />
          </el-form-item>
        </el-col>
        <el-col :span="span">
          <el-form-item label="新密码">
            <el-input type="password" placeholder="请输入新旧密码" show-password v-model.trim="form.new_password" />
          </el-form-item>
        </el-col>
        <el-col :span="span">
          <el-form-item label="确认密码">
            <el-input type="password" placeholder="请输入确认密码" show-password v-model.trim="form.check_password" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button type="info" @click="close">取消</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </template>
  </vab-dialog>
</template>

<script lang="ts" setup>
defineOptions({
  name: 'ChangePassword',
})

import { ElMessageBox } from 'element-plus'
import { update_password } from '/@/api/user'
const $baseMessage = inject<any>('$baseMessage')
const $baseConfirm = inject<any>('$baseConfirm')
const formRef = ref<any>(null)
const title = ref<string>('修改密码')
const dialogFormVisible = ref<boolean>(false)
const form = reactive<any>({})
const span = 20
const width = '380px'

//自定义保存数据
const save = () => {
  console.log(form)
  if (!form.old_password) {
    ElMessageBox.alert('请输入原密码', '提示', {
      confirmButtonText: '确定',
    })
    return false
  }
  if (!form.new_password) {
    ElMessageBox.alert('请输入新密码', '提示', {
      confirmButtonText: '确定',
    })
    return false
  }
  if (form.new_password.length < 6) {
    ElMessageBox.alert('请至少输入六位密码', '提示', {
      confirmButtonText: '确定',
    })
    return false
  }
  if (form.old_password == form.new_password) {
    ElMessageBox.alert('新密码与旧密码不能相同', '提示', {
      confirmButtonText: '确定',
    })
    return false
  }
  if (!form.check_password) {
    ElMessageBox.alert('请输入确认密码', '提示', {
      confirmButtonText: '确定',
    })
    return false
  }
  if (form.new_password != form.check_password) {
    ElMessageBox.alert('两次密码输入不一致', '提示', {
      confirmButtonText: '确定',
    })
    return false
  }
  $baseConfirm('确定修改密码吗？', null, async () => {
    const { msg }: any = await update_password(form.old_password, form.new_password)
    $baseMessage(msg, 'success', 'hey')
    dialogFormVisible.value = false
  })
}
//通用显示弹窗
const showDialog = (res: any) => {
  dialogFormVisible.value = true
}
defineExpose({
  showDialog,
})
//通用关闭弹窗
const close = () => {
  formRef.value.clearValidate()
  formRef.value.resetFields()
  dialogFormVisible.value = false
}
</script>
<style scoped>
.el-col {
  margin: 5px 0;
}
</style>
